package com.alen.sun.controller;

import com.alen.sun.bean.Admin;
import com.alen.sun.bean.PageBean;
import com.alen.sun.bean.Result;
import com.alen.sun.dao.AdminMapper;
import com.alen.sun.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/admins")
@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminMapper adminMapper;

    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @PostMapping
    @ResponseBody
    public Result addAdmin(@RequestBody Admin admin) {
        Boolean flag = adminService.addAdmin(admin);
        if(flag) {
            return Result.success();
        }else {
            return Result.error("添加失败");
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Admin admin){
        Boolean flag = adminService.login(admin);
        if(flag) {
            return Result.success();
        }else {
            Admin judge = adminMapper.selectPhoneNum(admin);
            if(judge != null){
                return Result.error("账号或密码错误");
            }else {
                return Result.error("该管理员不存在");
            }
        }
    }


    /**
     * 修改管理员信息
     * @param admin
     * @return
     */
    @PutMapping
    @ResponseBody
    public Result updateAdmin(@RequestBody Admin admin) {
        Boolean flag = adminService.updateAdmin(admin);
        if(flag) {
            return Result.success();
        }else {
            return Result.error("修改管理员信息失败");
        }
    }

    /**
     * 删除管理员
     * @param admin
     * @return
     */
    @DeleteMapping
    @ResponseBody
    public Result deleteAdmin(@RequestBody Admin admin) {
        Boolean flag = adminService.deleteAdmin(admin);
        if(flag) {
            return Result.success();
        }else {
            return Result.error("删除管理员失败");
        }
    }

    /**
     * 分类查询
     * @param requestParams
     * @return
     */
    @PostMapping("/selectByPage")
    @ResponseBody
    public Result page(@RequestBody Map<String, Integer> requestParams) {
        Integer page = requestParams.getOrDefault("page", 1);
        Integer pageSize = requestParams.getOrDefault("pageSize", 10);
        PageBean pageBean = adminService.page(page, pageSize);
        return Result.success(pageBean);
    }


    //批量删除
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/ids")
    @ResponseBody
    public Result deleteByIds(@RequestBody List<String> ids) {
        Boolean flag = adminService.deleteByIds(ids);
        if(flag){
            return Result.success();
        }else {
            return Result.error("批量删除失败");
        }

    }



}
